package worm

import (
	"cloud_worm/wormweb/controllers/ctrconfig"
	"cloud_worm/wormweb/controllers/ctrutil"
	"cloud_worm/util/proto/ujson"
	"cloud_worm/util/uhttp"
	"github.com/astaxie/beego/logs"
	"fmt"
	"io/ioutil"
	"encoding/json"
	"net"

)

type GrayRouterController struct {
	ctrconfig.LoginCtr
}

func (g *GrayRouterController) Get()  {
	g.Manager()

	confs, err := ctrutil.ResourceSet().GetGrayConfig()
	if err != nil {
		logs.Error(fmt.Sprintf("get gray config error: %s", err.Error()))
		data := map[string]interface{}{"total": 0, "data": ujson.GrayConfig{}}
		g.Data["json"] = uhttp.CreateOkResponse(data)
		g.ServeJSON()
		return
	}

	data := map[string]interface{}{"total": len(confs), "data": confs}
	g.Data["json"] = uhttp.CreateOkResponse(data)
	g.ServeJSON()
	return
}

func (g *GrayRouterController) Post()  {
	g.Manager()

	body, err := ioutil.ReadAll(g.Ctx.Request.Body)
	if err != nil {
		g.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, err.Error(), nil)
		g.ServeJSON()
		return
	}
	var gConfig ujson.GrayConfig
	if err = json.Unmarshal(body, &gConfig); err != nil {
		logs.Error(fmt.Sprintf("gray config json unmarshal error: %s", err.Error()))
		g.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, "gray config json unmarshal err.", nil)
		g.ServeJSON()
		return
	}

	if net.ParseIP(gConfig.LocalIP) == nil || gConfig.Target == "" {
		logs.Error("gray config ip parse or target error")
		g.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, "gray config ip or target err.", nil)
		g.ServeJSON()
		return
	}

	if err := ctrutil.ResourceSet().PostGrayConfig(gConfig.LocalIP, gConfig); err != nil {
		logs.Error(fmt.Sprintf("gray config post error: %s", err.Error()))
		g.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, "gray config post error.", nil)
		g.ServeJSON()
		return
	}

	g.Data["json"] = uhttp.CreateOkResponse(nil)
	g.ServeJSON()
	return
}